package com.burningtower.shiro;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.burningtower.entity.User;
import com.burningtower.service.*;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class UserRealm extends AuthorizingRealm {
    @Autowired
    private IUserService userService;
    @Autowired
    private IUserRoleService userRoleService;
    @Autowired
    private IRoleService roleService;
    @Autowired
    private IRoleResourceService roleResourceService;
    @Autowired
    private IResourceService resourceService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String username = (String) principalCollection.getPrimaryPrincipal();
        User user = userService.selectOne(new EntityWrapper<>(new User(username)));
        Long[] roleIds = userRoleService.selectRoleIdByUserId(user.getId());
        Set<String> roles=new HashSet<>();
        Set<String> permissions=new HashSet<>();
        for(Long roleId:roleIds){
            roles.add(roleService.selectById(roleId).getName());
            List<Long> resourceIds = roleResourceService.selectResourceIdListByRoleId(roleId);
            for(Long resourceId:resourceIds){
                String url=resourceService.selectById(resourceId).getUrl();
                if (!"".equals(url)){
                    permissions.add(url);
                }
            }
        }
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo(roles);
        info.setStringPermissions(permissions);
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = (String) token.getPrincipal();
        User user = userService.selectOne(new EntityWrapper<>(new User(username)));
        AuthenticationInfo info=new SimpleAuthenticationInfo(username,user.getPassword(), ByteSource.Util.bytes("test"),getName());
        return info;
    }
}
